package coms.mianshi.reference;

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: item_02
 * @description:
 * @author: LL
 * @create: 2021-03-02 09:42
 */
public class Test {
    /**
     * 强引用
     * 在ArrayList类中定义了一个私有的变量elementData数组，
     * 在调用方法清空数组时可以看到为每个数组内容赋值为null。
     * 不同于elementData=null，强引用仍然存在，避免在后续调用 add()等方法添加元素时进行重新的内存分配。
     * 使用如clear()方法中释放内存的方法对数组中存放的引用类型特别适用，这样就可以及时释放内存。
     */
    public static void hardReference() {
        final String str = "abc";
        final List<String> list = new ArrayList<String>();
        list.add(str);
    }

    //软引用
    public static void softReference() {
        System.out.println("开始");
        A a = new A();
        SoftReference<A> sr = new SoftReference<A>(a);
        a = null;
        if (sr != null) {
            a = sr.get();
        } else {
            a = new A();
            sr = new SoftReference<A>(a);
        }
        System.out.println("结束");
    }

    //弱引用
    public static void weakReference() {
        final Car car = new Car(22000, "green");
        final WeakReference<Car> carWeak = new WeakReference<Car>(car);
        int i = 0;
        while (true) {
            if (carWeak.get() != null) {
                i++;
                //System.out.println("car===" + car);
                System.out.println("Object is alive for " + i + " loops - " + carWeak);
            } else {
                System.out.println("Object has been collected.");
                break;
            }
        }
    }

    public static void main(final String[] args) {
        weakReference();
    }
}

class A {
    int[] a;

    public A() {
        this.a = new int[100000000];
    }
}

class Car {
    private double price;
    private String color;

    public Car(final double price, final String color) {
        this.price = price;
        this.color = color;
    }

    public double getPrice() {
        return this.price;
    }

    public void setPrice(final double price) {
        this.price = price;
    }

    public String getColor() {
        return this.color;
    }

    public void setColor(final String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Car{" +
                "price=" + this.price +
                ", color='" + this.color + '\'' +
                '}';
    }
}
